import { useResponsive } from '@/theme/hooks';
import TodoItem from './components/TodoITem';
import { useRouter } from '@/router/hooks';
import { useEffect, useMemo, useState } from 'react';
// import { todoList } from '@/types/know/constants';
import {
  BaseQuestionType,
  Category,
  GovStatisType,
  KnowCollection,
  KnowSimilarityCollection,
  QuestionType,
  Todo,
  TodoGov,
} from '@/types/know/know';
import knowService from '@/api/services/knowService';
import { useScrollPagination } from '@/hooks/use-pagination/useVirtualScrollPagination';
import KnowItem from './components/KnowItem';
import MarkModal from './sub-pages/govern/components/MarkModal';
import FileCompareModal from './sub-pages/document/components/FileCompareModal';
import datasetService from '@/api/services/datasetService';
import { message } from 'antd';
import ChangeExpiredTimeModal from './sub-pages/document/components/ChangeExpiredTimeModal';
import { OpType } from '@/types/enum';
import './styles/know-gov.scss';
import SubPageHeader from './components/SubPageHeader';
import { useLocation } from 'react-router-dom';

import Govern from './sub-pages/govern';
import Document from './sub-pages/document';
import EmptyTip from '@/components/EmptyTip';

const todoList: Todo[] = [
  {
    title: '问题回答治理',
    subTitle: '问题处理',
    // route: '/know/know-gov/govern',
    route: 'govern',
    key: 'questionsTotal',
    actionTitle: '立即治理',
    actionTip: '待处理',
    tip: (
      <div>
        <p>包括对未知问、点踩问和高频问的治理。</p>
        <p>
          <span className="font-bold">未知问治理</span>
          ：未知问是指系统或知识库中尚未涉及或覆盖的问题。
        </p>
        <p>
          <span className="font-bold">点踩问治理</span>
          ：点踩问是指用户反馈或投诉的不准确、误导性或低质量的问题。
        </p>
        <p>
          <span className="font-bold">高频问治理</span>：高频问是指用户频繁提出的问题。
        </p>
      </div>
    ),
  },
  {
    title: '知识库文档治理',
    subTitle: '知识处理',
    // route: '/know/know-gov/document',
    route: 'document',
    key: 'collectionsTotal',
    actionTitle: '立即治理',
    actionTip: '待处理',
    tip: (
      <div>
        <p>包括对重复知识和老化知识的治理。</p>
        <p>
          <span className="font-bold">重复知识治理</span>
          ：处理文档上传中存在的一些重复文档。
        </p>
        <p>
          <span className="font-bold">老化知识治理</span>
          ：处理过期文档。
        </p>
      </div>
    ),
  },
  // {
  //   title: '词条治理',
  //   subTitle: '词条管理',
  //   route: '/know/know-gov/entry',
  //   key: 'termsTotal',
  //   actionTitle: '去管理',
  //   actionTip: '已添加',
  //   tip: (
  //     <div>
  //       <p>包括对专业词、同义词、敏感词的管理。</p>
  //       <p>
  //         <span className="font-bold">专业词管理</span>
  //         ：指对特定行业、学科或领域中常用的专业术语进行管理和规范化。
  //       </p>
  //       <p>
  //         <span className="font-bold">同义词管理</span>
  //         ：指对具有相同或相近含义的词语进行管理和统一。
  //       </p>
  //       <p>
  //         <span className="font-bold">敏感词管理</span>
  //         ：指对可能引发争议、冲突或不当关注的词语进行管理和过滤。
  //       </p>
  //     </div>
  //   ),
  // },
  // {
  //   title: '审核发布',
  //   subTitle: '审核发布',
  //   route: '/know/know-gov/approval',
  //   key: 'auditTotal',
  //   actionTitle: '去审核',
  //   actionTip: '待审核',
  //   tip: '对已标注答案的问题进行审核发布',
  // },
];

/**
 * 知识治理模块
 */
const KnowGov = () => {
  const [markModalVisible, setMarkModalVisible] = useState(false);
  const [fileCompareModalVisible, setFileCompareModalVisible] = useState(false);
  const [changeExpiredTimeModalVisible, setChangeExpiredTimeModalVisible] = useState(false);
  const [currentTodo, setCurrentTodo] = useState<TodoGov | null>(null);
  const router = useRouter();
  const [govStatisics, setGovStatisics] = useState<GovStatisType>({
    questionsTotal: -1,
    collectionsTotal: -1,
    termsTotal: -1,
    auditTotal: -1,
  });

  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const appId = queryParams.get('appId') || '';

  const [activePage, setActivePage] = useState<string>('overview');

  const todoItemList = useMemo(() => {
    return todoList.map((item, index) => {
      return (
        <TodoItem
          key={index}
          title={item.title}
          actionTitle={item.actionTitle}
          actionTip={item.actionTip}
          count={govStatisics[item.key]}
          tip={item.tip}
          className="m-1 select-none rounded-xl bg-[#F7F8FA] p-6 lg:p-0"
          onClick={() => {
            console.log(item.route);
            setActivePage(item.route);
            // router.push(item.route);
          }}
          // route={item.route}
        />
      );
    });
  }, [todoList, govStatisics]);

  const getGovStatisics = async () => {
    try {
      const res = await knowService.getGovStatisics({
        app_id: appId,
      });
      setGovStatisics(res);
    } catch (error) {
      console.error(error);
    }
  };

  const { data, ScrollData, total, setTotal, refreshList, setData } = useScrollPagination(
    knowService.getTodoGovList,
    {
      pageSize: 15,
      // app_id: appId,
      params: {
        app_id: appId,
      },
    },
  );

  const onModalCancel = () => {
    setMarkModalVisible(false);
    setFileCompareModalVisible(false);
    setCurrentTodo(null);
  };

  const delExpireCollection = async (item: KnowCollection) => {
    try {
      // await datasetService.deleteDatasetCollection(item._id); //原来的接口
      await datasetService.deleteDatasetFile({
        // fileIds: [item?.fileId],
        ids: [item?._id],
      });
      message.success('删除成功');
      refreshData();
    } catch (error) {
      console.error(error);
    }
  };

  const onHandleClicked = (todo: TodoGov, type: OpType = OpType.update) => {
    setCurrentTodo(todo);
    switch (todo.category) {
      case Category.ConflictCollection:
      case Category.DuplicateCollection:
        setFileCompareModalVisible(true);
        break;
      case Category.ExpireCollection:
        switch (type) {
          case OpType.delete:
            delExpireCollection((todo as KnowCollection)!);
            break;
          case OpType.update:
            setChangeExpiredTimeModalVisible(true);
            break;
        }
        break;
      case Category.FeedbackQuestion:
      case Category.FeedbackGoodQuestion:
      case Category.FrequentQuestion:
      case Category.UnknownQuestion:
        setMarkModalVisible(true);
        break;
      default:
        break;
    }
  };

  const changeExpiredTimeConfirm = async (expiredTime: string) => {
    try {
      await knowService.postUpdateExpired({
        collection_id: (currentTodo as KnowCollection)?._id!,
        expired_time: expiredTime,
      });
      message.success('修改成功');
      setChangeExpiredTimeModalVisible(false);
      refreshData();
    } catch (error) {
      console.error(error);
    }
  };

  const onMarkCompleted = () => {
    refreshData();
  };

  const updateCurrentCollection = (collection: KnowSimilarityCollection | KnowCollection) => {
    const todo = collection as KnowSimilarityCollection | KnowCollection;
    if (todo.isDeleted || (todo?.duplicateList && todo?.duplicateList.length <= 0)) {
      setData((prev) => {
        return prev.filter((item) => item._id !== currentTodo?._id);
      });
      setCurrentTodo(null);
      setFileCompareModalVisible(false);
    } else {
      setCurrentTodo(collection);
    }
  };

  const refreshData = () => {
    try {
      getGovStatisics();
      refreshList();
    } catch (error) {
      console.error(error);
    }
  };

  // const onCompareCompleted = () => {
  //   getGovStatisics();
  //   setData((prev) => {
  //     return prev.filter((item) => item._id !== currentTodo?._id);
  //   });
  //   setTotal((prev) => prev - 1);
  // };

  // useEffect(() => {
  //   getGovStatisics();
  // }, []);

  useEffect(() => {
    activePage == 'overview' && refreshData();
    console.log(activePage);
  }, [activePage]);

  return (
    <div className={`flex h-full flex-col overflow-hidden bg-[#FFF]`}>
      {activePage == 'overview' && (
        <>
          <div className="h-10">
            <SubPageHeader canBack={false} />
          </div>
          <div
            className={`mt-2 grid h-full w-full flex-grow overflow-y-auto md:grid-cols-1 lg:grid-cols-3`}
          >
            <div className="col-span-2 h-full rounded-xl bg-[#FFF]">
              <div className={`grid h-full grid-cols-1 grid-rows-2 gap-2 p-4`}>{todoItemList}</div>
            </div>
            <div className="flex h-96 w-full flex-col overflow-hidden rounded-xl bg-[#FFF] p-2 px-4 md:col-span-2 lg:col-span-1 lg:h-full">
              <div className=" mt-4 text-base font-semibold text-[#1D2129]">
                待治理<span className="font-normal">（{total === 0 ? '-' : total}）</span>
              </div>
              {total === 0 && (
                <div className="flex h-full items-center justify-center">
                  <EmptyTip />
                </div>
              )}
              {total !== 0 && (
                <ScrollData>
                  <div className="gap-2">
                    {data.map((item) => (
                      <KnowItem
                        todo={item}
                        key={item?._id || item?.keyAnswerId}
                        onHandle={onHandleClicked}
                      />
                    ))}
                  </div>
                </ScrollData>
              )}
            </div>
          </div>
        </>
      )}
      {activePage == 'govern' && (
        <Govern
          onBack={() => {
            setActivePage('overview');
          }}
        />
      )}
      {activePage == 'document' && (
        <Document
          onBack={() => {
            setActivePage('overview');
          }}
        />
      )}
      {/* <div className="col-span-2 h-full rounded-xl bg-[#FFF]">
          <div className={`grid h-full grid-cols-1 grid-rows-2 gap-2 p-2`}>{todoItemList}</div>
        </div> */}
      <MarkModal
        type={
          currentTodo?.category == Category.UnknownQuestion
            ? QuestionType.Unknown
            : currentTodo?.category === Category.FeedbackQuestion ||
              currentTodo?.category === Category.FeedbackGoodQuestion
            ? QuestionType.Feedback
            : QuestionType.Frequent
        }
        data={(currentTodo as BaseQuestionType)!}
        open={markModalVisible}
        refresh={refreshData}
        onCancel={onModalCancel}
        completed={onMarkCompleted}
      />
      <FileCompareModal
        open={fileCompareModalVisible}
        collection={(currentTodo as KnowSimilarityCollection)!}
        onCancel={onModalCancel}
        completed={onMarkCompleted}
        refresh={refreshData}
        setCollection={updateCurrentCollection}
      />
      <ChangeExpiredTimeModal
        open={changeExpiredTimeModalVisible}
        defaultDate={(currentTodo as KnowCollection)?.expiredTime}
        onCancel={() => {
          setChangeExpiredTimeModalVisible(false);
        }}
        onConfirm={changeExpiredTimeConfirm}
      />
    </div>
  );
};

export default KnowGov;
